package com.wish.g1.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.wish.g1.common.core.config.SmsConfig;
import com.wish.g1.common.core.web.domain.AjaxResult;
import com.wish.g1.system.api.domain.SysUser;
import com.wish.g1.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/sms")
@RestController
public class SmsController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ISysUserService userService;
    @Autowired
    Redisson redisson;

    /**
     * 短信发送接口
     * @param phone
     * @return
     * @throws Exception
     */
    @GetMapping("/send/{phone}")
    public AjaxResult send(@PathVariable String phone) throws Exception {


        // String code = RandomUtil.randomNumbers(4);
        // redisTemplate.opsForValue().set("code:"+phone,code,2, TimeUnit.MINUTES);
        // System.out.println("----------" + code);
        // String result = SmsConfig.send(phone, code);

        String lockKey = "lock:"+phone;
        RLock lock = redisson.getLock(lockKey);
        String result = null;
        try {
            lock.lock();
            String code = RandomUtil.randomNumbers(4);
            redisTemplate.opsForValue().set("code:"+phone,code,2, TimeUnit.MINUTES);
            // result = SmsConfig.send(phone, code);
            log.info("手机号：{},验证码：{}",phone,code);
            result = code;
        }catch (Exception e){}
        finally {
            lock.unlock();
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/login")
    public AjaxResult login(String phone,String code){
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(phone);
        String s1 = userService.checkPhoneUnique(sysUser);
        if (s1.equals("1")){
            return new AjaxResult(201,"手机号已存在");
        }
        String s = (String) redisTemplate.opsForValue().get("code:" + phone);
        if (!code.equals(s)){
            AjaxResult.error("验证码错误");
        }
        return AjaxResult.success("注册成功");
    }

}
